package com.dhcc.DRGsHosp.infra.util;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

/**
 * @title		:PropertiesUtil.java
 * @description	:
 * @author		:lileizheng
 * @date		:2016年9月27日
 * @version     :1.0
 * @copyright   :DHCC 2013-2014 
 */
public class PropertiesUtil {
	public static void updateProperties(String fileName,Map<String, String> keyValueMap) { 
		String path = PropertiesUtil.class.getClassLoader().getResource("/").getPath();
        //getResource方法使用了utf-8对路径信息进行了编码，当路径中存在中文和空格时，他会对这些字符进行转换，这样，  
		//得到的往往不是我们想要的真实路径，在此，调用了URLDecoder的decode方法进行解码，以便得到原始的中文及空格路径。  
        Properties props = null;  
        BufferedWriter bw = null;  
  
        try {  
        	// 写入属性文件  
        	path = URLDecoder.decode(path,"utf-8");
        	bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path+fileName))); 
			props = PropertiesLoaderUtils.loadProperties(new ClassPathResource(fileName));  
			for (String key : keyValueMap.keySet())
			    props.setProperty(key, keyValueMap.get(key));  
			props.store(bw, "");
	    } catch (IOException e) {
	    	e.printStackTrace();
	    } finally {  
	        try {  
	            bw.close();  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        }  
	    }  
	} 

	public static Object getProperties(String fileName, String key){  
	    Properties props = new Properties();  
	    try {  
	        props=PropertiesLoaderUtils.loadAllProperties(fileName); 
	        return props.get(key); 
	    } catch (IOException e) {  
	        System.out.println(e.getMessage());  
	    }
		return null;  
	}
	
	public static Properties getProperties(String fileName){  
	    Properties props = new Properties();
	    List<Map<Object, Object>> list = new LinkedList<>();
	    try {  
	        props=PropertiesLoaderUtils.loadAllProperties(fileName); 
	        return props;
	    } catch (IOException e) {  
	        System.out.println(e.getMessage());  
	    }
		return null;  
	}
}
